package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.CheckedCarItemAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.utils.BitmapUtil;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.GralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.RxGralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.dialog.QRCodeDialog;
import com.bjesc_b2c.app.appraiset.widget.dialog.TipDialog;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.BasicDropDownPop;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.google.gson.Gson;
import com.rxretrofit_build.CarPhotoID;
import com.rxretrofit_build.util.CustomLog;
import com.rxretrofit_build.util.MapUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import master_bean.CheckedCarItemBean;
import master_bean.SinglePhotoUpBean;
import rx.Observable;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

/**
 * Created by lenovo on 2017/2/24.
 * 车身合影
 */

public class PhotographsActivity extends BaseActivity implements MultiItemTypeAdapter.OnItemClickListener, TipDialog.CallBack, View.OnClickListener {
    @InjectView(R.id.recycler_photographs)
    RecyclerView photoRecycler;

    private CheckedCarItemAdapter itemAdapter;
    private List<CheckedCarItemBean> itemBeanList;
    private SelectPhotoPop photoPop;
    private TipDialog tipDialog;
    private int currentIndex;
    private List<String> fileList;
    private boolean isCommit;
    private boolean isSave;
    private BasicDropDownPop basicPop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photographs);
        ButterKnife.inject(this);
        basicPop = new BasicDropDownPop(this, this);
        getData();
    }

    private void getData() {
        HashMap<String, Object> build = new MapUtil()
                .put("id", CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()))
                .put("class_id", CarPhotoID.photographsID)
                .put("attr_id", CarPhotoID.PHOTOGRAPHS)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).getSinglePhoto()
                , new BaseSubscriber<TokenBean<SinglePhotoUpBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<SinglePhotoUpBean> o) {
                        if (o.getStatus_code() == 9) {
                            isSave = false;
                        } else if (o.getStatus_code() == 0) {
                            isSave = true;
                        }
                        getItemList(o.getData());
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    private void getItemList(SinglePhotoUpBean data) {
        itemBeanList = new ArrayList<>();
        fileList = new ArrayList<>();
        if (data != null && data.getImg_info() != null && data.getImg_info().size() > 0) {
            for (int i = 0; i < data.getImg_info().size(); i++) {
                fileList.add(TimeListUilts.subUrl(data.getImg_info().get(i))); //将文件名添加到集合，以后需要用来删除的
                itemBeanList.add(new CheckedCarItemBean(data.getImg_info().get(i), false));
                //如果以后显示多张，这里需要判断最后一个，然后设置true
            }
        } else {
            itemBeanList.add(new CheckedCarItemBean("", false));
        }
        initViews();
    }

    private void initViews() {
        photoPop = new SelectPhotoPop(this, popListener);
        tipDialog = new TipDialog(this, this);

        photoRecycler.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, itemBeanList);
        photoRecycler.setAdapter(itemAdapter);
        itemAdapter.setOnItemClickListener(this);
    }

    @OnClick({R.id.iv_return, R.id.tv_save_info, R.id.btn_previous_page, R.id.btn_commit, R.id.rlty_title})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:
                finish();
                break;
            case R.id.tv_save_info:
                isCommit = false;
                saveInfo();
                break;
            case R.id.btn_previous_page:
                startIntent(new Intent(PhotographsActivity.this, ComprehensiveEvaluationActivity.class), true);
                break;
            case R.id.btn_commit:
                tipDialog.show();
                break;
            case R.id.rlty_car_form:        //车源图片
                startIntent(new Intent(PhotographsActivity.this, CarSourceActivity.class), true);
                break;
            case R.id.rlty_car_Framework:   //骨架
                startIntent(new Intent(PhotographsActivity.this, CarFrameworkImageActivity.class), true);
                break;
            case R.id.rlty_car_appearance:  //外观
                startIntent(new Intent(PhotographsActivity.this, CarSurfaceItemActivity.class), true);
                break;
            case R.id.rlty_car_interior:    //内饰
                startIntent(new Intent(PhotographsActivity.this, CarOrnamentsItemActivity.class), true);
                break;
            case R.id.rlty_car_damage:      //配置
                startIntent(new Intent(PhotographsActivity.this, DeviceActivity.class), true);
                break;
            case R.id.rlty_car_comprehensive:   //综合评估
                startIntent(new Intent(PhotographsActivity.this, ComprehensiveEvaluationActivity.class), true);
                break;
            case R.id.rlty_car_photo:       //合影
                basicPop.dismiss();
                break;
            case R.id.rlty_title:
                basicPop.showAsDropDown(findViewById(R.id.rlty_title));
                break;
        }
    }

    private void saveInfo() {
        SinglePhotoUpBean bean = new SinglePhotoUpBean();
        bean.setImg_info(getUpLoadImgList());
        bean.setAttr_id(CarPhotoID.PHOTOGRAPHS);
        bean.setId(CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()));
        HashMap<String, Object> build = new MapUtil()
                .put("data", new Gson().toJson(bean))
                .build();

        Observable<TokenBean<SinglePhotoUpBean>> tokenBeanObservable = null;
        if (isCommit) {
            tokenBeanObservable = RxRequest.getClient(this, build).create(IApiActivityRequest.class).commitInfo();
        } else {
            tokenBeanObservable = RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveCarPhoto();
        }

        RxRequest.request(ShowType.SHOW, tokenBeanObservable
                , new BaseSubscriber<TokenBean<SinglePhotoUpBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<SinglePhotoUpBean> o) {
                        if (!isCommit) {
                            new QRCodeDialog(PhotographsActivity.this, o.getData().getCode_url()).show();
                        }
//                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    /**
     * 将图片存到一个集合里面准备上传,并且提交到阿里云
     *
     * @return
     */
    private List<String> getUpLoadImgList() {
        List<String> photoList = new ArrayList<>();
        for (int i = 0; i < itemBeanList.size(); i++) {    //循环上传图片到阿里
            if (!TextUtils.isEmpty(itemBeanList.get(i).getPhoto())) {
                if (!itemBeanList.get(i).getPhoto().contains("http")) {
                    String fileName = TimeListUilts.getObjectKey() + ".png";
                    AliYunUtils.aLiYunUpLoadFuncation(
                            this,
                            CarPhotoID.PHOTOGRAPHS,       //图片ID
                            fileName,                           //图片名
                            itemBeanList.get(i).getPhoto()     //图片路径
                            , null);
                    photoList.add(fileName);
                } else {
                    photoList.add(TimeListUilts.subUrl(itemBeanList.get(i).getPhoto()));
                }
            }
        }
        return photoList;
    }


    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
                    GralleryFinalUtils.openCamera(gralleryCallBack);
                    break;
                case R.id.rlty_select_album:    //选择相册
                    RxGralleryFinalUtils.openRadioImage(PhotographsActivity.this, rxGalleryCallBack);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };


    private RxGralleryFinalUtils.RxGalleryFinalCallBack rxGalleryCallBack = new RxGralleryFinalUtils.RxGalleryFinalCallBack() {
        @Override
        public void onEvent(ImageRadioResultEvent imageRadioResultEvent) {

            Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(imageRadioResultEvent.getResult().getOriginalPath());
            Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
            BitmapUtil.saveBitmapToLocal(sbitmap1,imageRadioResultEvent.getResult().getOriginalPath());
            refreshImage(imageRadioResultEvent.getResult().getOriginalPath(), currentIndex);
        }
    };

    private GalleryFinal.OnHanlderResultCallback gralleryCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (reqeustCode == GralleryFinalUtils.CAMERA) {

                Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(resultList.get(0).getPhotoPath());
                Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
                BitmapUtil.saveBitmapToLocal(sbitmap1,resultList.get(0).getPhotoPath());
                refreshImage(resultList.get(0).getPhotoPath(), currentIndex);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    protected void refreshImage(String url, int index) {
        itemBeanList.set(index, new CheckedCarItemBean(url, true));
        itemAdapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        currentIndex = position;
        if (TextUtils.isEmpty(itemBeanList.get(position).getPhoto())) {
            //跳转相机
            photoPop.showAtLocation(findViewById(R.id.llty_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            //跳转大图
            Intent bigIntent = new Intent(PhotographsActivity.this, BigCarSourcePhotoActivity.class);
            bigIntent.putExtra("classId", CarPhotoID.photographsID);
            bigIntent.putExtra("sourceId", CarPhotoID.PHOTOGRAPHS);
            bigIntent.putExtra("title", "车辆合影");
            bigIntent.putExtra("photoUrl", itemBeanList.get(position).getPhoto());
            if (fileList != null && fileList.size() > 0) {
                bigIntent.putExtra("fileName", TimeListUilts.subUrl(itemBeanList.get(position).getPhoto()));
            }
            bigIntent.putExtra("isSave", isSave);
            startIntent(bigIntent, 26);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CustomLog.d("requestCode =" + requestCode + ", resultCode = " + requestCode);
        if (resultCode == 26) {
            if (!TextUtils.isEmpty(itemBeanList.get(currentIndex).getPhoto())) {
                itemBeanList.set(currentIndex, new CheckedCarItemBean("", false));
            }
            itemAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    /**
     * 确定保存回调
     */
    @Override
    public void callBack() {
        isCommit = true;
        saveInfo();
        tipDialog.dismiss();
    }
}
